﻿Imports IDServer
Imports System
Imports System.IO
Imports System.String
Imports System.Data
Imports System.Data.SqlClient
Imports UserDataGridView
Imports System.Threading
Imports CrystalDecisions.CrystalReports


Public Class Frm_SALRetailRejected

    Implements IDServer.IDServer.IDServer


    Public ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp
    Private mTableD As DataTable
    Private DetailDS As DataSet
    Private MasterDS As DataSet
    Private mTableC As DataTable
    Private bFind As Boolean
    Private WithEvents MainForm As Frm_MainForm

    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainForm
        End Get
        Set(ByVal value As Frm_MainForm)
            MainForm = value
        End Set
    End Property

#Region "interface"


    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd
        If AddEnable = False Then
            MessageBox.Show("對不起，您沒有新增權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If

        If Me.TabControl1.SelectedIndex = 0 Then
            Me.TabControl1.SelectedIndex = 1
        End If
        ClearText()
        SetEnable(True)
        Me.DateTimePicker1.Value = DateTime.Now.Date
        ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd
        MainForm.BtnEnable(False)
    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel
        If Me.TabControl1.SelectedIndex = 0 Then
        Else
            If MasterDS.Tables(0).Rows.Count <= 0 Then
                bFind = False
            Else
                bFind = True
                FillText(Me.DGV_Master.CurrentRow.Cells("BackOrdeNo").Value)
            End If
        End If
        SetEnable(False)
        MainForm.BtnEnable(bFind)
        MainForm.ToolStripFilter.Enabled = False
        MainForm.ToolStripFind.Enabled = False
        ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete

        Try
            If DeleteEnable = False Then
                MessageBox.Show("對不起，您沒有刪除權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If


        Catch ex As Exception
            MsgBox("ActionDelete:" & ex.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit
        If EditEnable = False Then
            MessageBox.Show("對不起，您沒有修改權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If

        If Me.TabControl1.SelectedIndex = 0 Then

        Else

        End If
        SetEnable(True)
        ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit
        MainForm.BtnEnable(False)
    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport

    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter

    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint

    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave
        If BtnActionSave() = True Then
            Return True
        End If
    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect
        BtnActionFind()
    End Function

#End Region


#Region "TabControlPage2"

    Private Sub BindMasterGrid()

        Try
            Dim mTable As New DataTable
            With mTable
                .Columns.Add("BackOrdeNo")
                .Columns.Add("SaleOrdeNo")
                .Columns.Add("WriteOrdeNo")
                .Columns.Add("CustermNo")
                .Columns.Add("GoodsCount")
                .Columns.Add("GoodsMoney")
                .Columns.Add("BackCount")
                .Columns.Add("BackMoney")
                .Columns.Add("DeDuctMoney")
                .Columns.Add("BackDate")
                .Columns.Add("ShopNo")
                .Columns.Add("CounterNo")
                .Columns.Add("remark")
                .Columns.Add("OperatePerson")
                .Columns.Add("OperateDate")
            End With
            MasterDS = New DataSet

            MasterDS.Tables.Add(mTable)
            Me.DGV_Master.DataSource = MasterDS.Tables(0)

            With Me.DGV_Master
                For i As Integer = 0 To .Columns.Count - 1
                    Dim mKey As String = .Columns(i).Name
                    Dim CaptionStr As String = BindHash(0).Item(mKey)
                    .Columns(i).HeaderText = CaptionStr
                Next
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells
                .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            End With
        Catch ex As Exception
            MsgBox("BindMasterGrid:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub BindDetailGrid()

        Try
            Dim mTable As New DataTable
            With mTable
                .Columns.Add("ID")
                .Columns.Add("GoodsBarCode", GetType(String))
                .Columns.Add("GoodsCode", GetType(String))
                .Columns.Add("SupperItem", GetType(String))
                .Columns.Add("GoodsName", GetType(String))
                .Columns.Add("GoodsColor", GetType(String))
                .Columns.Add("GoodsSize", GetType(String))
                .Columns.Add("GoodsCount", GetType(Decimal))
                .Columns.Add("SaleMoney", GetType(Decimal))
                .Columns.Add("SalePrice", GetType(String))
                .Columns.Add("GoodsCount1", GetType(Decimal))
            End With
            DetailDS = New DataSet
            DetailDS.Tables.Add(mTable)
            Me.DGV_Detail.DataSource = DetailDS.Tables(0)

            With Me.DGV_Detail
                For i As Integer = 0 To .Columns.Count - 1
                    Dim mKey As String = .Columns(i).Name
                    Dim CaptionStr As String = BindHash(1).Item(mKey)
                    .Columns(i).HeaderText = CaptionStr
                    If .Columns(i).Name = "GoodsCount" Then
                        .Columns(i).ReadOnly = False
                        .Columns(i).DefaultCellStyle.BackColor = Color.LightYellow
                    Else
                        .Columns(i).ReadOnly = True
                        .Columns(i).DefaultCellStyle.BackColor = Color.LightGray
                    End If
                Next
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                .MultiSelect = False
                .Columns("SalePrice").Visible = False
                .Columns("GoodsCount1").Visible = False
                .Columns("ID").Visible = False
            End With

        Catch ex As Exception
            MsgBox("BindDetailGrid:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub BindBackGrid()

        Try
            mTableC = New DataTable
            With mTableC
                .Columns.Add("ID")
                .Columns.Add("GoodsBarCode", GetType(String))
                .Columns.Add("GoodsCode", GetType(String))
                .Columns.Add("SupperItem", GetType(String))
                .Columns.Add("GoodsName", GetType(String))
                .Columns.Add("GoodsColor", GetType(String))
                .Columns.Add("GoodsSize", GetType(String))
                .Columns.Add("GoodsCount", GetType(Decimal))
                .Columns.Add("SaleMoney", GetType(Decimal))
                .Columns.Add("SalePrice", GetType(String))
            End With

            Me.DGV_Sum.DataSource = mTableC

            With Me.DGV_Sum
                For i As Integer = 0 To .Columns.Count - 1
                    Dim mKey As String = .Columns(i).Name
                    Dim CaptionStr As String = BindHash(1).Item(mKey)
                    .Columns(i).HeaderText = CaptionStr
                    If .Columns(i).Name = "GoodsCount" Then
                        .Columns(i).ReadOnly = True
                        .Columns(i).DefaultCellStyle.BackColor = Color.LightYellow
                    Else
                        .Columns(i).ReadOnly = True
                        .Columns(i).DefaultCellStyle.BackColor = Color.LightGray
                    End If
                Next
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                .MultiSelect = False
                .Columns("SalePrice").Visible = False
                .Columns("ID").Visible = False
            End With

        Catch ex As Exception
            MsgBox("BindDetailGrid:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    ''' <summary>
    ''' 綁定HashTable
    ''' </summary>
    ''' <param name="mIndex"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function BindHash(Optional ByVal mIndex As Integer = 0) As Hashtable
        Try
            Dim mHash As New Hashtable
            With mHash
                Select Case mIndex
                    Case 0
                        .Add("BackOrdeNo", "退貨單號")
                        .Add("SaleOrdeNo", "銷售單號")
                        .Add("WriteOrdeNo", "手寫單號")
                        .Add("CustermNo", "客戶")
                        .Add("GoodsCount", "原數量")
                        .Add("GoodsMoney", "原金額")
                        .Add("BackCount", "退貨數量")
                        .Add("BackMoney", "退貨金額")
                        .Add("DeDuctMoney", "折扣金額")
                        .Add("BackDate", "退貨日期")
                        .Add("ShopNo", "店鋪名稱")
                        .Add("CounterNo", "櫃台")
                        .Add("remark", "備注")
                        .Add("OperatePerson", "操作人員")
                        .Add("OperateDate", "操作日期")
                    Case 1
                        .Add("ID", "ID")
                        .Add("GoodsBarCode", "貨品條碼")
                        .Add("GoodsCode", "貨品編碼")
                        .Add("SupperItem", "供應商編碼")
                        .Add("GoodsName", "貨品名稱")
                        .Add("GoodsColor", "貨品顏色")
                        .Add("GoodsSize", "貨品規格")
                        .Add("GoodsCount", "貨品數量")
                        .Add("SaleMoney", "總金額")
                        .Add("SalePrice", "SalePrice")
                        .Add("GoodsCount1", "GoodsCount1")
                End Select
            End With
            Return mHash
        Catch ex As Exception
            MsgBox("BindHash:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
            Return Nothing
        End Try
    End Function

    Private Function ReturnWhereExp()
        Dim sql As String = " where 1=1 "

        If Me.txtCustermNo.Text.Trim <> "" Then
            sql &= "  and CustermNo like  '%" & Me.txtCustermNo.Text.Trim & "%'"
        End If

        If Me.txtShopNo.Text.Trim <> "" Then
            sql &= " and ShopNo like '%" & Me.txtShopNo.Text.Trim & "%'"
        End If

        If Me.txtWriteOrdeNo.Text.Trim <> "" Then
            sql &= "  and WriteOrdeNo like '%" & Me.txtWriteNo.Text.Trim & "%'"
        End If

        If Me.TextBox13.Text.Trim <> "" Then
            sql &= "  and BackDate ='" & Me.TextBox13.Text.Trim & "' "
        End If

        If Me.TextBox7.Text.Trim <> "" Then
            sql &= "  and  SaleOrdeNo like  '%" & Me.TextBox7.Text.Trim & "%' "
        End If

        If Me.txt_BackOrdeNo.Text.Trim <> "" Then
            sql &= "  and  BackOrdeNo like '%" & Me.txt_BackOrdeNo.Text.Trim & "%'"
        End If

        If Me.TextBox11.Text.Trim <> "" Then
            sql &= "  and OperatePerson = '" & Me.TextBox11.Text.Trim & "'"
        End If

        If Me.TextBox12.Text.Trim <> "" Then
            sql &= "  and  OperateDate='" & Me.TextBox12.Text.Trim & "' "
        End If

        Return sql
    End Function

    Private Sub BtnActionFind()

        Try

            Dim sql As String = ""

            Dim whereExp As String = ReturnWhereExp()


            sql = "select BackOrdeNo,SaleOrdeNo,WriteOrdeNo,CustermNo,GoodsCount,GoodsMoney,BackCount,BackMoney,DeDuctMoney,BackDate,ShopNo,CounterNo,remark,OperatePerson,OperateDate from Sal_PosBackMaster      " & whereExp
            MasterDS = New DataSet
            MasterDS = ReturnDataset(sql)
            Me.DGV_Master.DataSource = MasterDS.Tables(0)
        Catch ex As Exception
            MsgBox("BtnActionFind->>" & ex.ToString & ex.StackTrace, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    ''' <summary>
    ''' txtSaleNo回車事件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub txtPosSaleNo_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtPosSaleNo.KeyDown

        Dim sql As String
        Dim WhereStr As String
        Dim SaleOrdeNo As String
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                If e.KeyCode = Keys.Enter Then

                    If Me.txtPosSaleNo.Text.Length <= 0 Then Exit Sub

                    SaleOrdeNo = Me.txtPosSaleNo.Text

                    WhereStr = " and fSaleOrdeNo='" & SaleOrdeNo & "'"
                    sql = "select ID='',replace(a.fGoodsBarCode,'*','') as GoodsBarcode,b.Code as GoodsCode,b.Cnname as GoodsName,b.SupperItem,c.ColorSName as GoodsColor,d.SizeSname as GoodsSize,"
                    sql += " a.fSumCount as GoodsCount,a.fSumMoney as SaleMoney ,b.SalePrice,a.fSumCount as GoodsCount1"
                    sql += " from dbo.Sal_SaleOrdeB a left join dbo.BSC_Goods b on a.fGoodsBarCode=b.BarCode left join "
                    sql += " dbo.BSC_ColorDefine c on b.Color=c.ColorCode left join dbo.BSC_SizeDefine d on b.Spec=SizeCode where 1=1" & WhereStr

                    DetailDS = ReturnDataset(sql)
                    For i As Integer = 0 To DetailDS.Tables(0).Rows.Count - 1
                        DetailDS.Tables(0).Rows(i).Item("ID") = i + 1
                    Next
                    DetailDS.AcceptChanges()
                    Me.DGV_Detail.DataSource = DetailDS.Tables(0)

                    mTableC.Rows.Clear()
                    mTableC.AcceptChanges()
                    Me.DGV_Sum.DataSource = mTableC
                    Me.TextBox1.Text = Me.txtPosSaleNo.Text
                End If
            End If
        Catch ex As Exception
            MsgBox("txtSaleNo_KeyDown:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    ''' <summary>
    ''' 判斷退貨處理網格單元格的數據
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub DGV_Master_CellValidated(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV_Detail.CellValidated
        Me.LabError.Text = ""
        Me.LabError.Visible = False
        Me.DGV_Detail.Rows(e.RowIndex).ErrorText = Nothing
    End Sub

    ''' <summary>
    ''' 出錯處理事件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub DGV_Master_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DGV_Detail.CellValidating

        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                If e.ColumnIndex = 5 Then
                    Dim testInteger As Double
                    If Not e.FormattedValue.ToString.Length = 0 Then
                        If Not Double.TryParse(e.FormattedValue.ToString, testInteger) Then
                            Me.LabError.Visible = True
                            Me.LabError.Text = "輸入格式不正確，請重新輸入！"
                            Me.DGV_Detail.Rows(e.RowIndex).ErrorText = "錯誤"
                            e.Cancel = True
                        End If
                    Else
                        Me.LabError.Visible = True
                        Me.LabError.Text = "數量不能為空！"
                        Me.DGV_Detail.Rows(e.RowIndex).ErrorText = "錯誤"
                        e.Cancel = True
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox("DGV_Master_CellValidating:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    ''' <summary>
    ''' 單元格改變事件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub DGV_Master_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV_Detail.CellValueChanged
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then

                If e.ColumnIndex = 7 Then
                    Dim SalePrice As Double = 0
                    Dim GoodsCount As Double = 0
                    Dim GoodsCount1 As Double = 0
                    GoodsCount1 = Me.DGV_Detail.CurrentRow.Cells("GoodsCount1").Value

                    If Me.DGV_Detail.CurrentRow.Cells("SalePrice").Value Is System.DBNull.Value Then
                    Else
                        SalePrice = Convert.ToDouble(Me.DGV_Detail.CurrentRow.Cells("SalePrice").Value)
                    End If
                    If Me.DGV_Detail.CurrentRow.Cells("GoodsCount").Value Is System.DBNull.Value Then
                    Else
                        GoodsCount = Convert.ToDouble(Me.DGV_Detail.CurrentRow.Cells("GoodsCount").Value)
                    End If
                    If Not IsNumeric(GoodsCount) Then
                        Exit Sub
                    End If

                    If GoodsCount1 < GoodsCount Then
                        MsgBox("對不起，數量超出範圍，不能修改！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                        Me.DGV_Detail.CurrentRow.Cells("GoodsCount").Value = Format(GoodsCount1, "#0.00")
                        Exit Sub
                    Else
                        If DetailDS.Tables(0).Rows.Count > 0 Then

                            Dim NewRow As DataRow = mTableC.NewRow
                            Dim Rows() As DataRow = mTableC.Select("GoodsBarCode='" & Me.DGV_Detail.CurrentRow.Cells("GoodsBarCode").Value & "'")
                            If Rows.Length > 0 Then
                                Rows(0).Item("GoodsCount") = Format(GoodsCount1 - GoodsCount, "#0.00")
                                Rows(0).Item("SaleMoney") = Format((GoodsCount1 - GoodsCount) * SalePrice, "#0.00")
                            Else
                                NewRow("ID") = mTableC.Rows.Count + 1
                                NewRow("GoodsBarCode") = Me.DGV_Detail.CurrentRow.Cells("GoodsBarCode").Value
                                NewRow("GoodsCode") = Me.DGV_Detail.CurrentRow.Cells("GoodsCode").Value
                                NewRow("SupperItem") = Me.DGV_Detail.CurrentRow.Cells("SupperItem").Value
                                NewRow("GoodsName") = Me.DGV_Detail.CurrentRow.Cells("GoodsName").Value
                                NewRow("GoodsColor") = Me.DGV_Detail.CurrentRow.Cells("GoodsColor").Value
                                NewRow("GoodsSize") = Me.DGV_Detail.CurrentRow.Cells("GoodsSize").Value
                                NewRow("GoodsCount") = Format(GoodsCount1 - GoodsCount, "#0.00")
                                NewRow("SaleMoney") = Format((GoodsCount1 - GoodsCount) * SalePrice, "#0.00")
                                NewRow("SalePrice") = Format(Me.DGV_Detail.CurrentRow.Cells("SalePrice").Value, "#0.00")
                                mTableC.Rows.Add(NewRow)
                            End If
                            mTableC.AcceptChanges()
                            Me.DGV_Sum.DataSource = mTableC
                            Me.DGV_Detail.CurrentRow.Cells("SaleMoney").Value = Convert.ToDouble(GoodsCount) * Convert.ToDouble(SalePrice)
                        End If
                        Me.txtBackCount.Text = Format(mTableC.Compute("sum(GoodsCount)", ""), "#0.00")
                        Me.txtBackMoney.Text = Format(mTableC.Compute("sum(SaleMoney)", ""), "#0.00")
                    End If
                End If

            End If

        Catch ex As Exception
            MsgBox("DGV_Master_CellValueChanged:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    ''' <summary>
    ''' 網格的鍵盤事件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub DGV_Detail_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DGV_Detail.KeyDown
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                If e.KeyCode = Keys.Delete Then

                    If DetailDS.Tables(0).Rows.Count <= 0 Then
                        MsgBox("對不起，沒有數據可移除！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                        Exit Sub
                    End If
                    Dim CurrentId As String = Me.DGV_Detail.CurrentRow.Cells("ID").Value

                    Dim SalePrice As Double = 0
                    Dim GoodsCount As Double = 0
                    Dim GoodsCount1 As Double = 0

                    If Me.DGV_Detail.CurrentRow.Cells("SalePrice").Value Is System.DBNull.Value Then
                    Else
                        SalePrice = Convert.ToDouble(Me.DGV_Detail.CurrentRow.Cells("SalePrice").Value)
                    End If

                    If Me.DGV_Detail.CurrentRow.Cells("GoodsCount").Value Is System.DBNull.Value Then
                    Else
                        GoodsCount = Convert.ToDouble(Me.DGV_Detail.CurrentRow.Cells("GoodsCount").Value)
                    End If

                    If Me.DGV_Detail.CurrentRow.Cells("GoodsCount1").Value Is System.DBNull.Value Then
                    Else
                        GoodsCount1 = Convert.ToDouble(Me.DGV_Detail.CurrentRow.Cells("GoodsCount1").Value)
                    End If

                    Dim NewRow As DataRow = mTableC.NewRow
                    Dim Rows() As DataRow = mTableC.Select("GoodsBarCode='" & Me.DGV_Detail.CurrentRow.Cells("GoodsBarCode").Value & "'")
                    If Rows.Length > 0 Then
                        Rows(0).Item("GoodsCount") = Format(GoodsCount1, "#0.00")
                        Rows(0).Item("SaleMoney") = Format(GoodsCount1 * SalePrice, "#0.00")
                    Else
                        NewRow("ID") = mTableC.Rows.Count + 1
                        NewRow("GoodsBarCode") = Me.DGV_Detail.CurrentRow.Cells("GoodsBarCode").Value
                        NewRow("GoodsCode") = Me.DGV_Detail.CurrentRow.Cells("GoodsCode").Value
                        NewRow("SupperItem") = Me.DGV_Detail.CurrentRow.Cells("SupperItem").Value
                        NewRow("GoodsName") = Me.DGV_Detail.CurrentRow.Cells("GoodsName").Value
                        NewRow("GoodsColor") = Me.DGV_Detail.CurrentRow.Cells("GoodsColor").Value
                        NewRow("GoodsSize") = Me.DGV_Detail.CurrentRow.Cells("GoodsSize").Value
                        NewRow("GoodsCount") = Format(Convert.ToDouble(Me.DGV_Detail.CurrentRow.Cells("GoodsCount").Value), "#0.00")
                        NewRow("SaleMoney") = Format((Convert.ToDouble(Me.DGV_Detail.CurrentRow.Cells("GoodsCount").Value)) * SalePrice, "#0.00")
                        NewRow("SalePrice") = Format(Me.DGV_Detail.CurrentRow.Cells("SalePrice").Value, "#0.00")
                        mTableC.Rows.Add(NewRow)
                    End If
                    mTableC.AcceptChanges()
                    Me.DGV_Sum.DataSource = mTableC
                    DeleteRowOfGrid(CurrentId, 0)
                    Me.txtBackCount.Text = Format(mTableC.Compute("sum(GoodsCount)", ""), "#0.00")
                    Me.txtBackMoney.Text = Format(mTableC.Compute("sum(SaleMoney)", ""), "#0.00")
                End If
            End If
        Catch ex As Exception
            MsgBox("DGV_Master_KeyDown:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    ''' <summary>
    ''' 刪除網格中的行
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function DeleteRowOfGrid(ByVal ID As String, ByVal index As Integer) As Boolean

        Try
            If index = 0 Then
                Dim Rows() As DataRow = DetailDS.Tables(0).Select("ID='" & ID & "'")

                If Rows.Length > 0 Then
                    DetailDS.Tables(0).Rows.Remove(Rows(0))
                End If
                DetailDS.AcceptChanges()
                Me.DGV_Detail.DataSource = DetailDS.Tables(0)
                Return True
            Else
                Dim Rows() As DataRow = mTableC.Select("ID='" & ID & "'")

                If Rows.Length > 0 Then
                    mTableC.Rows.Remove(Rows(0))
                End If
                mTableC.AcceptChanges()
                Me.DGV_Sum.DataSource = mTableC
                Return True
            End If

        Catch ex As Exception
            MsgBox("DeleteRowOfGrid:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    ''' <summary>
    ''' 保存數據
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub BtnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim SqlConn As New SqlClient.SqlConnection(ConnectionString)
        SqlConn.Open()
        Dim Sqlcmd As SqlClient.SqlCommand = SqlConn.CreateCommand
        Dim SqlTran As SqlClient.SqlTransaction = Nothing
        Dim SqlBulk As SqlClient.SqlBulkCopy
        Dim sql As String = ""
        Dim SumCount As Double
        Dim SumMoney As Double
        Try
            SqlTran = SqlConn.BeginTransaction
            Sqlcmd.Connection = SqlConn
            Sqlcmd.Transaction = SqlTran

            If mTableD.Rows.Count > 0 Then
                SumCount = mTableD.Compute("sum(GoodsCount)", "")
                SumMoney = mTableD.Compute("sum(SaleMoney)", "")
                sql = "Insert Into SAL_GoodsBACK(SaleOrdeNo,GoodsBarcode,GoodsCount,GoodsMoney,EditPerson,EditDate,EditCompute,shopNo)"
                sql += "select SaleOrdeNo,GoodsBarCode,GoodsCount,GoodsPrice,EditPerson='" & PubUserName & "',EditDate='" & Format(Now.Date, "yyyy-MM-dd") & "',EditCompute='" & My.Computer.Name & "',ShopNo='" & PubCompanyCode & "' from Sal_PosB where SaleOrdeNo='" & Me.txtPosSaleNo.Text & "'"
                With Sqlcmd
                    .CommandType = CommandType.Text
                    .CommandText = sql
                    .ExecuteNonQuery()
                End With

                sql = "Delete Sal_PosB where SaleOrdeNo='" & Me.txtPosSaleNo.Text & "'"
                With Sqlcmd
                    .CommandType = CommandType.Text
                    .CommandText = sql
                    .ExecuteNonQuery()
                End With

                sql = "Update Sal_PosA Set SumCount=" & SumCount & ",SumMoney=" & SumMoney & ",OrdeStatus=1,UpdateDate=convert(varchar(10),getdate(),21),UpdateComputer='" & My.Computer.Name & "'  where SaleOrdeNo='" & Me.txtPosSaleNo.Text & "'"
                With Sqlcmd
                    .CommandType = CommandType.Text
                    .CommandText = sql
                    .ExecuteNonQuery()
                End With
                Dim ColName As String = "SaleOrdeNo,GoodsBarCode,GoodsCount,GoodsPrice"
                Dim mDataTable As New DataTable
                SqlBulk = New SqlClient.SqlBulkCopy(SqlConn, SqlBulkCopyOptions.Default, SqlTran)
                SqlBulk.DestinationTableName = "dbo.Sal_PosB"
                SqlBulk.BulkCopyTimeout = 100
                SqlBulk.WriteToServer(mDataTable)
            Else
                Exit Sub
            End If
            SqlTran.Commit()
            MsgBox("操作成功!", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            Me.DGV_Detail.Columns(6).ReadOnly = True
            Me.DGV_Detail.Columns(6).DefaultCellStyle.BackColor = Color.LightGray
        Catch ex As Exception
            SqlTran.Rollback()
            MsgBox("BtnSave_Click:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    ''' <summary>
    ''' 初始化表並填充數據
    ''' </summary>
    ''' <param name="ColName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function InticntDataTable(ByVal ColName As String, ByVal BackOrdeNo As String, ByVal index As Integer) As DataTable
        Try
            Dim mTable As New DataTable
            Dim Str() As String = ColName.Split(",")
            With mTable
                For i As Integer = 0 To Str.Length - 1
                    .Columns.Add(Str(i))
                Next
            End With

            If index = 0 Then
                For Each Row As DataRow In DetailDS.Tables(0).Rows
                    Dim mRow As DataRow = mTable.NewRow
                    mRow("BackOrdeNo") = BackOrdeNo
                    mRow("GoodsBarCode") = "*" & Row("GoodsBarCode") & "*"
                    mRow("GoodsCount") = Row("GoodsCount") & ""
                    mRow("GoodsPrice") = Row("SaleMoney") & ""
                    mRow("builtDate") = ServerDate
                    mRow("BuiltPerson") = PubUserName
                    mRow("builtComputer") = My.Computer.Name
                    mTable.Rows.Add(mRow)
                Next
            ElseIf index = 1 Then

                Dim Tab As DataTable ''分兩種情況

                Tab = DirectCast(Me.DGV_Detail.DataSource, DataTable)

                For Each Row As DataRow In Tab.Rows

                    Dim mRow As DataRow = mTable.NewRow
                    mRow("BoNum") = BackOrdeNo
                    mRow("ItemNo") = Format(mTableC.Rows.Count + 1, "000")
                    mRow("PoNum") = Me.TextBox1.Text
                    mRow("PoNumItem") = ""
                    mRow("DeliverNo") = ""
                    mRow("GoodsBarcode") = "*" & Row("GoodsBarCode") & "*"
                    mRow("Batch") = ""
                    mRow("GoodsStatus") = "1"
                    mRow("Storeplace") = ""
                    mRow("Goodsamount") = Row("GoodsCount") & ""
                    mTable.Rows.Add(mRow)
                Next
            End If

            mTable.AcceptChanges()
            Return mTable
        Catch ex As Exception
            Return Nothing
            MsgBox("BtnSave_Click:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Private Function BtnActionSave() As Boolean
        Dim sql As String
        Dim SqlStr As String = ""
        Dim SqlConn As New SqlClient.SqlConnection()
        Dim Sqlcmd As New SqlClient.SqlCommand
        Dim SqlBulk As SqlClient.SqlBulkCopy
        Dim SaleOrdeNo As String = Me.TextBox1.Text
        Dim BackOrdeNo As String = ""
        Dim BoNum As String = ""
        Dim WriteOrdeNo As String = Me.txtWriteNo.Text
        Dim GoodsCount As Double = 0
        Dim GoodsMoney As Double = 0
        Dim BackCount As Double = Val(Me.txtBackCount.Text)
        Dim BackMoney As Double = Val(Me.txtBackMoney.Text)
        Dim DeDuctMoney As Double = 0
        Dim SumCount As Double
        Dim SumMoney As Double
        Dim BackDate As String = Me.DateTimePicker1.Value.Year.ToString & "-" & Format(Me.DateTimePicker1.Value.Month, "00") & "-" & Format(Me.DateTimePicker1.Value.Day, "00")
        Dim ShopNo As String = PubCompanyCode
        Dim CounterNo As String = ""
        Dim OperatePerson As String = PubUserName
        Dim OperateDate As String = ServerDate
        Dim OperateComputer As String = My.Computer.Name
        Dim Remark As String = Me.txtRemark.Text.Replace("'", "")

        SqlConn = GetConn()
        If SqlConn.State = ConnectionState.Closed Then
            SqlConn.Open()
        End If
        Dim SqlTran As SqlTransaction = SqlConn.BeginTransaction
        Try

            If DetailDS.Tables(0).Rows.Count > 0 Then
                SumCount = DetailDS.Tables(0).Compute("sum(GoodsCount)", "")
                SumMoney = DetailDS.Tables(0).Compute("sum(SaleMoney)", "")
            End If
            BackCount = SumCount
            BackMoney = SumMoney
            Me.txtBackCount.Text = BackCount
            Me.txtBackMoney.Text = BackMoney
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
                ''BackOrdeNo = AutoGetNo(PubCompanyCode, "BackOrdeNo", "Sal_PosBackMaster", 3)

                ''Modify By :huyang
                BackOrdeNo = Exec("exec ReturnBillNum 'Sal_PosBackMaster','BackOrdeNo','DGT'", E_ExecType.ExecuteScalar) & ""

                sql = "Insert Into Sal_PosBackMaster(BackOrdeNo,SaleOrdeNo,WriteOrdeNo,BackCount,BackMoney,BackDate,ShopNo,Remark,OperatePerson,OperateComputer) values('"
                sql += BackOrdeNo & "','" & SaleOrdeNo & "','" & WriteOrdeNo & "'," & BackCount & "," & BackMoney & ",'" & BackDate & "','"
                sql += ShopNo & "','" & Remark & "','" & OperatePerson & "','" & OperateComputer & "');"
                If Me.rdbSaleNo.Checked = True Then
                    sql += "Update Sal_PosA Set OrdeStatus=1,UpdateDate=convert(varchar(10),getdate(),21),UpdateComputer='" & My.Computer.Name & "'  where SaleOrdeNo='" & SaleOrdeNo & "'"
                End If
                If Me.rdbSaleNo2.Checked = True Then
                    sql += "Update Sal_SaleOrdeA Set fOrdeStatus='D' where fSaleOrdeNo='" & SaleOrdeNo & "';"
                    sql += "update Sal_InvoiceA set BillstatusID= 'D' where fsaleOrdeNo = '" & SaleOrdeNo & "'"

                End If

                With Sqlcmd
                    .Connection = SqlConn
                    .Transaction = SqlTran
                    .CommandType = CommandType.Text
                    .CommandText = sql
                    .ExecuteNonQuery()
                End With
                Dim ColName As String = "BackOrdeNo,GoodsBarcode,GoodsCount,GoodsPrice,builtDate,BuiltPerson,builtComputer"
                Dim mDataTable As DataTable = InticntDataTable(ColName, BackOrdeNo, 0)
                SqlBulk = New SqlClient.SqlBulkCopy(SqlConn, SqlBulkCopyOptions.Default, SqlTran)
                SqlBulk.DestinationTableName = "Sal_PosBackDetail"
                SqlBulk.BulkCopyTimeout = 100
                SqlBulk.WriteToServer(mDataTable)

                BoNum = AutoCreateBoNum(PubCompanyCode, "+", PubCompanyCode, "Stor_TradeMaster")
                SqlStr = "Insert Into Stor_TradeMaster(BoNum,TradeType,InOrOutType,toStore,BoStatus,OperatePerson,OperateComputer,DeliverDate) values('"
                SqlStr += BoNum & "','+','05','" & PubCompanyCode & "','A','" & PubUserName & "','" & My.Computer.Name & "',Convert(varchar(10),Getdate(),21))"
                With Sqlcmd
                    .Connection = SqlConn
                    .Transaction = SqlTran
                    .CommandType = CommandType.Text
                    .CommandText = SqlStr
                    .ExecuteNonQuery()
                End With

                ColName = ""
                ColName = "BoNum,ItemNo,PoNum,PoNumItem,DeliverNo,GoodsBarcode,Batch,GoodsStatus,Storeplace,Goodsamount"
                Dim mTable As DataTable = InticntDataTable(ColName, BoNum, 1)
                SqlBulk = New SqlClient.SqlBulkCopy(SqlConn, SqlBulkCopyOptions.Default, SqlTran)
                SqlBulk.DestinationTableName = "Stor_TradeDetail"
                SqlBulk.BulkCopyTimeout = 100
                SqlBulk.WriteToServer(mTable)

                AddToDataSet(BackOrdeNo, SaleOrdeNo, WriteOrdeNo, "", GoodsCount, GoodsMoney, BackCount, BackMoney, DeDuctMoney, BackDate, ShopNo, CounterNo, OperatePerson, OperateDate)
                Me.LabInfo.Text = BackOrdeNo
            ElseIf ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                sql = "Update Sal_PosBackMaster Set SaleOrdeNo='" & SaleOrdeNo & "',WriteOrdeNo='" & Me.txtWriteNo.Text & "',BackCount=" & BackCount & ",BackMoney=" & BackMoney & ",BackDate='" & BackDate & "',ShopNo='" & PubCompanyCode & "',Remark='" & Remark & "' where BackOrdeNo='" & Me.LabInfo.Text & "';"
                sql += "Delete Sal_PosBackDetail where BackOrdeNo='" & Me.LabInfo.Text & "'"
                With Sqlcmd
                    .Connection = SqlConn
                    .Transaction = SqlTran
                    .CommandType = CommandType.Text
                    .CommandText = SqlStr
                    .ExecuteNonQuery()
                End With
                Dim ColName As String = "BackOrdeNo,GoodsBarcode,GoodsCount,GoodsPrice,builtDate,BuiltPerson,builtComputer"
                Dim mDataTable As DataTable = InticntDataTable(ColName, BackOrdeNo, 0)
                SqlBulk = New SqlClient.SqlBulkCopy(SqlConn, SqlBulkCopyOptions.Default, SqlTran)
                SqlBulk.DestinationTableName = "Sal_PosBackDetail"
                SqlBulk.BulkCopyTimeout = 100
                SqlBulk.WriteToServer(mDataTable)

                SqlStr = "Update Stor_TradeMaster set UpdateDate='" & ServerDate & "',UpdatePerson='" & PubUserName & "',UpdateComputer='" & My.Computer.Name & "', DeliverDate=Convert(varchar(10),getdate(),21)     where BoNum='" & Me.LabBoNum.Text & "';"
                SqlStr += "Delete Stor_TradeDetail where BoNum='" & Me.LabBoNum.Text & "'"
                ColName = ""
                ColName = "BoNum,ItemNo,PoNum,PoNumItem,DeliverNo,GoodsBarcode,Batch,GoodsStatus,Storeplace,Goodsamount"
                Dim mTable As DataTable = InticntDataTable(ColName, BoNum, 1)
                SqlBulk = New SqlClient.SqlBulkCopy(SqlConn, SqlBulkCopyOptions.Default, SqlTran)
                SqlBulk.DestinationTableName = "Stor_TradeDetail"
                SqlBulk.BulkCopyTimeout = 100
                SqlBulk.WriteToServer(mTable)

            End If
            SqlTran.Commit()
            SqlConn.Close()
            MsgBox(IIf(ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd, My.Resources.AddSuccess, My.resources.EditSuccess), MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            Me.DGV_Master.DataSource = MasterDS.Tables(0)
            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
            SetEnable(False)
            bFind = True
            MainForm.BtnEnable(bFind)
        Catch ex As Exception
            SqlTran.Rollback()
            MsgBox("BtnActionSave:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally

        End Try

    End Function

    Private Sub AddToDataSet(ByVal BackOrdeNo As String, ByVal SaleOrdeNo As String, ByVal WriteOrdeNo As String, ByVal CustermNo As String, ByVal GoodsCount As Double, ByVal GoodsMoney As Double, ByVal BackCount As Double, ByVal BackMoney As Double, ByVal DeDuctMoney As Double, ByVal BackDate As String, ByVal shopNo As String, ByVal CounterNo As String, ByVal OperatePerson As String, ByVal OperateDate As String)

        Try
            If MasterDS Is Nothing Then Exit Sub
            Dim mRow As DataRow = MasterDS.Tables(0).NewRow
            mRow("BackOrdeNo") = BackOrdeNo
            mRow("SaleOrdeNo") = SaleOrdeNo
            mRow("WriteOrdeNo") = WriteOrdeNo
            mRow("CustermNo") = CustermNo
            mRow("GoodsCount") = GoodsCount
            mRow("GoodsMoney") = GoodsMoney
            mRow("BackCount") = BackCount
            mRow("BackMoney") = BackMoney
            mRow("DeDuctMoney") = DeDuctMoney
            mRow("BackDate") = BackDate
            mRow("shopNo") = shopNo
            mRow("CounterNo") = CounterNo
            mRow("OperatePerson") = OperatePerson
            mRow("OperateDate") = OperateDate
            MasterDS.Tables(0).Rows.Add(mRow)
            MasterDS.AcceptChanges()
        Catch ex As Exception
            MsgBox("AddToDataSet:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub EditToDataSet(ByVal BackOrdeNo As String, ByVal SaleOrdeNo As String, ByVal WriteOrdeNo As String, ByVal CustermNo As String, ByVal GoodsCount As Double, ByVal GoodsMoney As Double, ByVal BackCount As Double, ByVal BackMoney As Double, ByVal DeDuctMoney As Double, ByVal BackDate As String, ByVal shopNo As String, ByVal CounterNo As String, ByVal OperatePerson As String, ByVal OperateDate As String)

        Try
            If MasterDS Is Nothing Then Exit Sub
            Dim Rows() As DataRow = MasterDS.Tables(0).Select("BackOrdeNo='" & BackOrdeNo & "'")
            If Rows.Length > 0 Then
                For Each mRow As DataRow In Rows
                    mRow("BackOrdeNo") = BackOrdeNo
                    mRow("SaleOrdeNo") = SaleOrdeNo
                    mRow("WriteOrdeNo") = WriteOrdeNo
                    mRow("CustermNo") = CustermNo
                    mRow("GoodsCount") = GoodsCount
                    mRow("GoodsMoney") = GoodsMoney
                    mRow("BackCount") = BackCount
                    mRow("BackMoney") = BackMoney
                    mRow("DeDuctMoney") = DeDuctMoney
                    mRow("BackDate") = BackDate
                    mRow("shopNo") = shopNo
                    mRow("CounterNo") = CounterNo
                    mRow("OperatePerson") = OperatePerson
                    mRow("OperateDate") = OperateDate
                    MasterDS.AcceptChanges()
                Next
            End If
        Catch ex As Exception
            MsgBox("EditToDataSet:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub DeleteDataSet()

        Try

        Catch ex As Exception
            MsgBox("DeleteDataSet:" & ex.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub SetEnable(ByVal b As Boolean)
        Me.txtWriteNo.Enabled = b
        Me.txtRemark.Enabled = b
        Me.rdbSaleNo.Enabled = b
        Me.rdbSaleNo2.Enabled = b
        Me.DateTimePicker1.Enabled = b
        Me.TextBox1.Enabled = False
        Me.cmbOrdeType.Enabled = False
        Me.txtBackCount.Enabled = False
        Me.txtBackMoney.Enabled = False
        Me.txtPosSaleNo.Enabled = b And Me.rdbSaleNo.Checked
        Me.txtSaleOrdeNo.Enabled = b And Me.rdbSaleNo2.Checked
        Me.btnSelect.Enabled = b And Me.rdbSaleNo.Checked
        Me.btnSelect1.Enabled = b And Me.rdbSaleNo2.Checked
    End Sub

    Private Sub ClearText()
        Me.LabInfo.Text = ""
        Me.txtWriteNo.Text = ""
        Me.txtRemark.Text = ""
        Me.TextBox1.Text = ""
        Me.txtBackCount.Text = ""
        Me.txtBackMoney.Text = ""
        Me.cmbOrdeType.SelectedIndex = -1
        If DetailDS.Tables(0).Rows.Count > 0 Then
            DetailDS.Tables(0).Rows.Clear()
            Me.DGV_Detail.DataSource = DetailDS.Tables(0)
        End If
        If mTableC.Rows.Count > 0 Then
            mTableC.Rows.Clear()
            Me.DGV_Sum.DataSource = mTableC
        End If
    End Sub

    Private Sub LoadCombox()
        With Me.cmbOrdeType
            .Items.Add("POS銷售")
            .Items.Add("訂單銷售")
            .DropDownStyle = ComboBoxStyle.DropDownList
        End With
    End Sub

    Private Sub FillText(ByVal BackOrdeNo As String)

        Try
            Dim Rows() As DataRow = MasterDS.Tables(0).Select("BackOrdeNo='" & BackOrdeNo & "'")
            If Rows.Length > 0 Then
                Me.LabInfo.Text = BackOrdeNo
                Me.txtWriteNo.Text = Rows(0).Item("WriteOrdeNo") & ""
                Me.DateTimePicker1.Text = Rows(0).Item("BackDate") & ""
                Me.TextBox1.Text = Rows(0).Item("SaleOrdeNo") & ""
                Me.txtBackCount.Text = Rows(0).Item("BackCount") & ""
                Me.txtBackMoney.Text = Rows(0).Item("BackMoney") & ""
                Me.txtRemark.Text = Rows(0).Item("Remark") & ""

            End If

            Dim sql As String = ""
            Dim SqlStr As String = ""
            sql = "select ID='',Replace(a.GoodsBarcode,'*','') as GoodsBarCode,b.Code as GoodsCode,b.SupperItem,b.ShortName as GoodsName,c.ColorSName as GoodsColor,d.SizeSName as GoodsSize,a.Goodscount,a.GoodsPrice as SaleMoney from Sal_PosBackDetail a"
            sql += " inner join dbo.BSC_Goods b on a.GoodsBarcode=b.BarCode inner join BSC_ColorDefine c on b.Color=c.ColorCode inner join BSC_SizeDefine d on b.Spec=d.SizeCode where a.BackOrdeNo='" & BackOrdeNo & "';"

            SqlStr += "select a.BoNum,ID='',Replace(a.GoodsBarcode,'*','') as GoodsBarCode,b.Code as GoodsCode,b.SupperItem,b.ShortName as GoodsName,c.ColorSName as GoodsColor,d.SizeSName as GoodsSize,a.Goodsamount as GoodsCount,SaleMoney=a.Goodsamount*b.SalePrice from Stor_TradeMaster h inner join dbo.Stor_TradeDetail a on h.BoNum=a.BoNum inner join Sal_PosBackMaster g on a.PoNum=g.SaleOrdeNo"
            SqlStr += " inner join dbo.BSC_Goods b on a.GoodsBarcode=b.BarCode inner join BSC_ColorDefine c on b.Color=c.ColorCode inner join BSC_SizeDefine d on b.Spec=d.SizeCode where h.TradeType='+' and a.PoNum='" & Me.TextBox1.Text & "'"

            DetailDS = New DataSet
            DetailDS = ReturnDataset(sql)
            mTableC = ReturnDataset(SqlStr).Tables(0)
            For i As Integer = 0 To DetailDS.Tables(0).Rows.Count - 1
                DetailDS.Tables(0).Rows(i).Item("ID") = i + 1
            Next
            For i As Integer = 0 To mTableC.Rows.Count - 1
                mTableC.Rows(i).Item("ID") = i + 1
            Next
            Me.DGV_Detail.DataSource = DetailDS.Tables(0)
            Me.DGV_Sum.DataSource = mTableC
            Me.DGV_Sum.Columns("BoNum").Visible = False
            'Me.LabBoNum.Text = mTableC.Rows(0).Item("BoNum") & ""
        Catch ex As Exception
            MsgBox("FillText-->>" + ex.ToString & ex.StackTrace, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub ShowSelectWinform(ByVal index As Integer)

        Dim Frm_SelectSaleOrde As New Frm_SelectSaleOrde
        Dim sql As String = ""
        Dim SaleOrdeNo As String = ""
        Dim WhereStr As String = ""
        Try

            Frm_SelectSaleOrde.Index = index
            Frm_SelectSaleOrde.ShowDialog()
            If Frm_SelectSaleOrde.SaleOrdeNo.ToString.Length <= 0 Then
                Exit Sub
            End If
            SaleOrdeNo = Frm_SelectSaleOrde.SaleOrdeNo

            Me.TextBox1.Text = SaleOrdeNo
            Select Case index
                Case 0
                    WhereStr = " and SaleOrdeNo='" & SaleOrdeNo & "'"
                    sql = "select ID='',replace(a.GoodsBarcode,'*','') as GoodsBarCode,"
                    sql += " b.Code as GoodsCode,b.Cnname as GoodsName,b.SupperItem,c.ColorSName as GoodsColor,d.SizeSName as GoodsSize,"
                    sql += " a.GoodsCount,a.GoodsPrice as SaleMoney,b.SalePrice,a.GoodsCount as GoodsCount1"
                    sql += " from dbo.Sal_PosB a left join dbo.BSC_Goods b on a.GoodsBarCode=b.BarCode left join "
                    sql += " dbo.BSC_ColorDefine c on b.Color=c.ColorCode left join dbo.BSC_SizeDefine d on b.Spec=SizeCode where 1=1" & WhereStr
                Case 1
                    WhereStr = " and fSaleOrdeNo='" & SaleOrdeNo & "'"
                    sql = "select ID='',replace(a.fGoodsBarCode,'*','') as GoodsBarcode,b.Code as GoodsCode,b.Cnname as GoodsName,b.SupperItem,c.ColorSName as GoodsColor,d.SizeSname as GoodsSize,"
                    sql += " a.fSumCount as GoodsCount,a.fSumMoney as SaleMoney ,b.SalePrice,a.fSumCount as GoodsCount1"
                    sql += " from dbo.Sal_SaleOrdeB a left join dbo.BSC_Goods b on a.fGoodsBarCode=b.BarCode left join "
                    sql += " dbo.BSC_ColorDefine c on b.Color=c.ColorCode left join dbo.BSC_SizeDefine d on b.Spec=SizeCode where 1=1" & WhereStr
            End Select

            DetailDS = ReturnDataset(sql)
            For i As Integer = 0 To DetailDS.Tables(0).Rows.Count - 1
                DetailDS.Tables(0).Rows(i).Item("ID") = i + 1
            Next
            DetailDS.AcceptChanges()
            Me.DGV_Detail.DataSource = DetailDS.Tables(0)

            mTableC.Rows.Clear()
            mTableC.AcceptChanges()
            Me.DGV_Sum.DataSource = mTableC
        Catch ex As Exception
            ''MsgBox("ShowSelectWinform:" & ex.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Frm_SelectSaleOrde.Dispose()
        End Try

    End Sub

#End Region


#Region "Control Events"

    Private Sub Frm_SALRetailRejected_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        BindMasterGrid()
        BindDetailGrid()
        BindBackGrid()
        LoadCombox()
        SetEnable(False)
        ClearText()
    End Sub

    Private Sub rdbSaleNo_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rdbSaleNo.CheckedChanged

        Try

            Me.txtPosSaleNo.Enabled = True
            Me.btnSelect.Enabled = True
            Me.txtSaleOrdeNo.Enabled = False
            Me.btnSelect1.Enabled = False
            Me.cmbOrdeType.SelectedIndex = 0
        Catch ex As Exception
            MsgBox("rdbSaleNo_CheckedChanged:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub rdbSaleNo2_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rdbSaleNo2.CheckedChanged

        Try

            Me.txtPosSaleNo.Enabled = False
            Me.btnSelect.Enabled = False
            Me.txtSaleOrdeNo.Enabled = True
            Me.btnSelect1.Enabled = True
            Me.cmbOrdeType.SelectedIndex = 1
        Catch ex As Exception
            MsgBox("rdbSaleNo2_CheckedChanged:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub txtSaleNo1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)

        Dim sql As String
        Dim SaleNo As String
        Try

            If e.KeyCode = Keys.Enter Then

                sql = "select distinct(replace(a.GoodsBarCode,'*','')) as GoodsBarCode,a.SaleOrdeNo,b.Code as GoodsCode,b.CnName as GoodsName,c.ColorCName as GoodsColor,d.SizeSName as GoodsSize,a.GoodsCount,a.GoodsPrice as SaleMoney,e.SaleDate as BuyDate,b.SalePrice from dbo.Sal_PosB a left join BSC_Goods b on a.GoodsBarCode=b.BarCode inner join BSC_ColorDefine c on b.Color=c.ColorCode inner join BSC_SizeDefine d on b.Spec=d.SizeCode left join Sal_PosA e on a.SaleOrdeNo=e.SaleOrdeNo where a.SaleOrdeNo='" & SaleNo & "'"
                DetailDS = ReturnDataset(sql)
                Me.DGV_Detail.DataSource = DetailDS.Tables(0)
            End If

        Catch ex As Exception
            MsgBox("txtSaleNo1_KeyDown:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub btnFind_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFind.Click
        MainForm.ToolStripFind_Click(Nothing, Nothing)
    End Sub

    Private Sub DGV_Master_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGV_Master.DoubleClick
        Me.TabControl1.SelectedIndex = 1
    End Sub

    Private Sub TabControl1_Selected(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlEventArgs) Handles TabControl1.Selected
        Try
            If Not Me.TabControl1.SelectedTab Is Nothing Then
                Select Case Me.TabControl1.SelectedIndex
                    Case 0
                        IsFilter = True
                        IsExport = True
                    Case 1
                        If MasterDS.Tables(0).Rows.Count <= 0 Then
                        Else
                            Dim BackOrdeNo As String = Me.DGV_Master.CurrentRow.Cells("BackOrdeNo").Value
                            FillText(BackOrdeNo)
                        End If
                End Select
            End If
        Catch ex As Exception
            MsgBox("TabControl1_Selected-->>" + ex.ToString & ex.StackTrace, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub TabControl1_Selecting(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlCancelEventArgs) Handles TabControl1.Selecting
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                e.Cancel = True
            End If
        Catch ex As Exception
            MsgBox("TabControl1_Selecting-->>" + ex.ToString & ex.StackTrace, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub btnSelect_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSelect.Click

        Try
            ShowSelectWinform(Me.rdbSaleNo.Tag)

        Catch ex As Exception

        End Try

    End Sub

    Private Sub btnSelect1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSelect1.Click

        Try
            ShowSelectWinform(Me.rdbSaleNo2.Tag)
        Catch ex As Exception

        End Try

    End Sub

    Private Sub DGV_Sum_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DGV_Sum.KeyDown

        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                If e.KeyCode = Keys.Delete Then

                    If mTableC.Rows.Count <= 0 Then
                        MsgBox("對不起，沒有數據可移除！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                        Exit Sub
                    End If
                    Dim CurrentId As String = Me.DGV_Sum.CurrentRow.Cells("ID").Value

                    Dim SalePrice As Double = 0
                    Dim GoodsCount As Double = 0
                    Dim GoodsCount1 As Double = 0

                    If Me.DGV_Sum.CurrentRow.Cells("SalePrice").Value Is System.DBNull.Value Then
                    Else
                        SalePrice = Convert.ToDouble(Me.DGV_Sum.CurrentRow.Cells("SalePrice").Value)
                    End If

                    If Me.DGV_Sum.CurrentRow.Cells("GoodsCount").Value Is System.DBNull.Value Then
                    Else
                        GoodsCount = Convert.ToDouble(Me.DGV_Sum.CurrentRow.Cells("GoodsCount").Value)
                    End If

                    'If Me.DGV_Sum.CurrentRow.Cells("GoodsCount1").Value Is System.DBNull.Value Then
                    'Else
                    '    GoodsCount1 = Convert.ToDouble(Me.DGV_Sum.CurrentRow.Cells("GoodsCount1").Value)
                    'End If

                    Dim NewRow As DataRow = DetailDS.Tables(0).NewRow
                    Dim Rows() As DataRow = DetailDS.Tables(0).Select("GoodsBarCode='" & Me.DGV_Sum.CurrentRow.Cells("GoodsBarCode").Value & "'")
                    If Rows.Length > 0 Then
                        GoodsCount1 = Rows(0).Item("GoodsCount1")
                        Rows(0).Item("GoodsCount") = Format(GoodsCount1, "#0.00")
                        Rows(0).Item("SaleMoney") = Format(GoodsCount1 * SalePrice, "#0.00")
                    Else
                        NewRow("ID") = DetailDS.Tables(0).Rows.Count + 1
                        NewRow("GoodsBarCode") = Me.DGV_Sum.CurrentRow.Cells("GoodsBarCode").Value
                        NewRow("GoodsCode") = Me.DGV_Sum.CurrentRow.Cells("GoodsCode").Value
                        NewRow("SupperItem") = Me.DGV_Sum.CurrentRow.Cells("SupperItem").Value
                        NewRow("GoodsName") = Me.DGV_Sum.CurrentRow.Cells("GoodsName").Value
                        NewRow("GoodsColor") = Me.DGV_Sum.CurrentRow.Cells("GoodsColor").Value
                        NewRow("GoodsSize") = Me.DGV_Sum.CurrentRow.Cells("GoodsSize").Value
                        NewRow("GoodsCount") = Format(Convert.ToDouble(Me.DGV_Sum.CurrentRow.Cells("GoodsCount").Value), "#0.00")
                        NewRow("SaleMoney") = Format((Convert.ToDouble(Me.DGV_Sum.CurrentRow.Cells("GoodsCount").Value)) * SalePrice, "#0.00")
                        DetailDS.Tables(0).Rows.Add(NewRow)
                    End If
                    mTableC.AcceptChanges()
                    Me.DGV_Detail.DataSource = DetailDS.Tables(0)
                    DeleteRowOfGrid(CurrentId, 1)
                    If mTableC.Rows.Count > 0 Then
                        Me.txtBackCount.Text = Format(mTableC.Compute("sum(GoodsCount)", ""), "#0.00")
                        Me.txtBackMoney.Text = Format(mTableC.Compute("sum(SaleMoney)", ""), "#0.00")
                    Else
                        Me.txtBackCount.Text = "0.00"
                        Me.txtBackMoney.Text = "0.00"
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox("DGV_Sum_KeyDown:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub txtSaleOrdeNo_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtSaleOrdeNo.KeyDown

        Dim sql As String
        Dim WhereStr As String
        Dim SaleOrdeNo As String
        Try

            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                If e.KeyCode = Keys.Enter Then
                    If Me.txtSaleOrdeNo.Text.Length <= 0 Then Exit Sub
                    SaleOrdeNo = Me.txtSaleOrdeNo.Text

                    WhereStr = " and SaleOrdeNo='" & SaleOrdeNo & "'"
                    sql = "select ID='',replace(a.GoodsBarcode,'*','') as GoodsBarCode,"
                    sql += " b.Code as GoodsCode,b.Cnname as GoodsName,b.SupperItem,c.ColorSName as GoodsColor,d.SizeSName as GoodsSize,"
                    sql += " a.GoodsCount,a.GoodsPrice as SaleMoney,b.SalePrice,a.GoodsCount as GoodsCount1"
                    sql += " from dbo.Sal_PosB a left join dbo.BSC_Goods b on a.GoodsBarCode=b.BarCode left join "
                    sql += " dbo.BSC_ColorDefine c on b.Color=c.ColorCode left join dbo.BSC_SizeDefine d on b.Spec=SizeCode where 1=1" & WhereStr

                    DetailDS = ReturnDataset(sql)
                    For i As Integer = 0 To DetailDS.Tables(0).Rows.Count - 1
                        DetailDS.Tables(0).Rows(i).Item("ID") = i + 1
                    Next
                    DetailDS.AcceptChanges()
                    Me.DGV_Detail.DataSource = DetailDS.Tables(0)

                    mTableC.Rows.Clear()
                    mTableC.AcceptChanges()
                    Me.DGV_Sum.DataSource = mTableC
                    Me.TextBox1.Text = Me.txtSaleOrdeNo.Text
                End If
            End If
        Catch ex As Exception
            MsgBox("txtSaleOrdeNo_KeyDown:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub TabPage2_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles TabPage2.Paint
        Dim mWidth As Integer = Me.TabPage2.Width
        Dim mHeight As Integer = Me.TabPage2.Height
        e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
        e.Graphics.FillRectangle(New Drawing2D.LinearGradientBrush(New Point(0, 0), New Point(mWidth, mHeight), Color.White, Color.Gray), 0, 0, mWidth, mHeight)
    End Sub

    Private Sub TabPage1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles TabPage1.Paint
        Dim mWidth As Integer = Me.TabPage1.Width
        Dim mHeight As Integer = Me.TabPage1.Height
        e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
        e.Graphics.FillRectangle(New Drawing2D.LinearGradientBrush(New Point(0, 0), New Point(mWidth, mHeight), Color.White, Color.Gray), 0, 0, mWidth, mHeight)
    End Sub

#End Region



    Private Sub GroupBox3_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GroupBox3.Enter

    End Sub

    Private Sub GroupBox1_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub
End Class
